package servlet;

import dao.UserDao;
import model.User;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    public UserDao userDao = new UserDao();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if(name == null || "".equals(name) || password == null || "".equals(password)){
            resp.getWriter().write("账号或密码不能为空");
            return;
        }
        //验证账号密码是否正确
        User user = userDao.selectByName(name);
        if(user == null || user.getId() <= 0){
            resp.getWriter().write("账号不存在，请重新确认");
            return;
        }
        //判断密码是否正确
        if(!password.equals(user.getPassword())){
            resp.getWriter().write("密码错误");
            return;
        }
        //正确登录，跳转到博客列表页
        //把用户的信息存储在Session里
        //如果没有session，就创建session；如果存在，就返回
        HttpSession session = req.getSession(true);
        //把密码置空
        user.setPassword("");
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }

    /**
     * 判断用户是否登录，如果登录，返回用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户登录信息
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if(session == null || session.getAttribute("user") == null){
            //说明用户未登录，返回一个空对象
            resp.getWriter().write(JSONUtil.toJson(new User()));
            return;
        }
        User user = (User)session.getAttribute("user");
        if(user == null || user.getId() <= 0){
            resp.getWriter().write(JSONUtil.toJson(new User()));
            return;
        }
        //返回用户信息
        resp.getWriter().write(JSONUtil.toJson(user));
    }
}
